package com.didispace.chapter56.interceptor;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.didispace.chapter56.utils.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

@Slf4j
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 1.在调用控制器方法前，拦截
     * <p>
     * 返回值为false，代表拦截
     * 返回值为true，代表放行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("---------------------开始进入请求地址拦截----------------------------");
        //注释掉为了swagger-ui接口测试可以正常使用
//        DatagoUser user = (DatagoUser) UserContext.getSession().getAttribute("user");
        String user = (String) request.getSession().getAttribute("user");
        RestResult restResult = new RestResult();
        if (!Objects.isNull(user)) {
            //检测redis中是否含有sessionId
            String loginSessionId = redisTemplate.opsForValue().get(request.getSession().getAttribute("user"));
            if (loginSessionId != null && loginSessionId.equals(request.getSession().getId())) {
                return true;
            } else {
                restResult.setMessage("该账号在另一台设备上登录，您被强制下线，请您重新登陆！！！");
            }
        } else {
            restResult.setMessage("请您先进行登录");
        }
        restResult.setCode(-2);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSONUtil.toJsonStr(restResult));
        return false;
    }

    /**
     * 2.在调用控制器方法后，拦截（在生成视图之前）
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        log.info("=============进入拦截器了,请求处理后，渲染ModelAndView前调用。=================================");
        // TODO Auto-generated method stub
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


    /**
     * 3.在视图生成之后（后台所有所有逻辑都完成后）
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("=============进入拦截器了,渲染ModelAndView后调用。=================================");
        // TODO Auto-generated method stub
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
